import sys
import sqlite3
import wx
import cPickle
import os

from fno_strategy import setlogger
setlogger.setlogger()

from fno_strategy import StrategyPanel, model

class MainPanel(wx.Panel):
    def __init__(self, parent):
        wx.Panel. __init__(self, parent)

        self.filePath = None
        
        sizer = wx.BoxSizer(wx.VERTICAL)
        self.strategyPanel = StrategyPanel.StrategyPanel(self)
        sizer.Add(self.strategyPanel, proportion=1, flag=wx.ALL|wx.EXPAND)
                
        self.SetSizer(sizer)
        
    def setModel(self, model):
        self.model = model
        self.strategyPanel.setModel(self.model)
        
    def openModel(self):
        dlg = wx.FileDialog(
                self, message="Open strategy file",
                defaultDir=".",
                defaultFile="",
                wildcard="Strategy File(*.str)|*.str",
                style=wx.OPEN |wx.CHANGE_DIR
                )
    
        if dlg.ShowModal() != wx.ID_OK:
            dlg.Destroy()
            return
            
        path = dlg.GetPath()
        self.openModelFile(path)
        dlg.Destroy()
        
    def openModelFile(self, path):
        path = os.path.abspath(path)
        model = cPickle.load(open(path, "rb"))
        self.setModel(model)
        self.filePath = path
        self.GetParent().updateTitle()
    
    def saveModel(self):
        if self.filePath is None:
            self.saveAsModel()
            return
        
        f = open(self.filePath, "wb")
        cPickle.dump(self.model, f)
        f.close()
        
        self.GetParent().updateTitle()
        
    def saveAsModel(self):
        dlg = wx.FileDialog(
            self, message="Save Strategy File", defaultDir=".", 
            defaultFile="", wildcard="Strategy File(*.str)|*.str", style=wx.SAVE
        )

        if dlg.ShowModal() != wx.ID_OK:
            dlg.Destroy()
            return
        
        self.filePath = dlg.GetPath()
        self.saveModel()
        dlg.Destroy()
        
class MainFrame(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None, -1, style=wx.DEFAULT_FRAME_STYLE, size=(600,500))
        self._setMenu()
        self.mainPanel = MainPanel(self)
        self.updateTitle()
        
        if len(sys.argv) >= 2 and os.path.exists(sys.argv[1]):
            self.mainPanel.openModelFile(sys.argv[1])
        else:
            self.mainPanel.setModel(model.Model())
            
        self.Show()
        
    def updateTitle(self):
        title="Fno Strategy"
        if self.mainPanel.filePath:
            fileName = os.path.basename(self.mainPanel.filePath)
            fileName = "".join(fileName.split(".")[:-1])
            title += " - "+fileName
        self.SetTitle(title)
        
    def _setMenu(self):
        menuBar = wx.MenuBar()
        
        fileMenu = wx.Menu()
        fileMenu.Append(wx.ID_OPEN, "&Open", "Open strategy file")
        fileMenu.Append(wx.ID_SAVE, "&Save", "Save strategy file")
        fileMenu.Append(wx.ID_SAVEAS, "&Save As", "Save as")
        
        wx.EVT_MENU(self, wx.ID_OPEN, self._fileOpen)
        wx.EVT_MENU(self, wx.ID_SAVE, self._fileSave)
        wx.EVT_MENU(self, wx.ID_SAVEAS, self._fileSaveAs)
        
        menuBar.Append(fileMenu, "&File")
        
        self.SetMenuBar(menuBar) 
        
    def _fileOpen(self, event):
        self.mainPanel.openModel()
    
    def _fileSave(self, event):
        self.mainPanel.saveModel()
    
    def _fileSaveAs(self, event):
        self.mainPanel.saveAsModel()
    
class FnoApp(wx.App):
    def OnInit(self):
        frame = MainFrame()
        self.SetTopWindow(frame)

        frame.Show(True)
        return True
    
def main():
    app = FnoApp(0)
    app.MainLoop()
    
